import React from 'react'
import {connect,} from 'react-redux'

import {Modal, WhiteSpace} from "antd-mobile"
import GiftPopupTab from "./GiftPopupTab/GiftPopupTab"
import GiftList from "./GiftList/GiftList"
import GiftPopupBtns from "./GiftPopupBtns/GiftPopupBtns"
import GiftCount from "./GiftCount/GiftCount"

import {getMyGiftReq, getUserDetailReq} from "../../../../../../apis/goApis";

import RoundGiftIcon from "../../../../../../res/images/web/chat-room/Gift2@2x.png"
import LocalStorageService from "../../../../../../utils/LocalStorageService";
import SmallCoinIcon from "../../../../../../res/images/web/shared/coin.png";
import bagSrc from "../../../../../../res/images/web/together/我的背包@2x.png"
import giftSrc from "../../../../../../res/images/web/together/道具@2x.png"

const storage = LocalStorageService

class TogetherGiftPopup extends React.Component {

    constructor(props) {
        super(props)
        this.uid = storage.get('userid')
        this.state = {
            tabs: [
                {title: '送给主队', active: true,},
                {title: '送给客队', active: false,},
            ],
            curIndex: 0,
            // curTab: {title: '礼物', active: true,},
            list: [],
            myGiftList: [],
            total: 0,
            selectGift: null,
            giftSend: false,
            gold: 0,
            showPack: false,
        }
    }

    componentDidMount() {

        if (this.uid) {
            this.getUserDetail()
                .then(() => {
                    this.getGift()
                })
        }

    }

    getUserDetail = () => {
        // return this.props.fetchUserDetail({uid: this.uid,})
        return getUserDetailReq({uid: this.uid,}, false,)
            .then((resp) => {
                if (resp.data.ok) {
                    this.setState({
                        gold: resp.data.ok.Gold,
                    })
                }
            })
    }

    getGift = () => {
        getMyGiftReq({
            uid: this.uid,
        }).then((resp) => {
            if (resp && resp.data && resp.data.prop) {
                const data = resp.data
                const list = data.prop.sort((g1, g2) => g1.Gold - g2.Gold)

                const myList = []
                const packet = data.packet
                packet.map(([id, count,]) => {
                    if (count > 0) {
                        const i = list.findIndex(gift => gift.Id === id)
                        if (i > -1) {
                            const gift = {...list[i], count,}
                            myList.push(gift)
                        }
                    }
                })
                if (list.length > 0) {
                    list[0].selected = true
                }
                if (myList.length > 0) {
                    myList[0].selected = true
                }
                this.setState({
                    list,
                    myList,
                    selectGift: this.state.showPack ? myList[0] : list[0],
                    total: 1,
                })
            }
        })
    }

    onTabClick = (tab) => {
        const tabs = this.state.tabs
        const curIndex = tabs.findIndex(t => t.title === tab.title)
        tabs.forEach((tab, index) => {
            tab.active = index === curIndex
        })
        this.setState({
            tabs: [...tabs,],
            curIndex,
            curTab: tab,
        })
    }

    onGiftSelected = (gift) => {
        const showPack = this.state.showPack
        const list = showPack ? this.state.myList : this.state.list
        const selectIndex = list.findIndex(g => g.Id === gift.Id)
        list.forEach((gift, index) => {
            gift.selected = index === selectIndex
        })
        if (showPack) {
            this.setState({
                myList: list,
                selectGift: gift,
            })
        } else {
            this.setState({
                list: list,
                selectGift: gift,
            })
        }

    }

    changeTotal = offset => {
        const result = this.state.total + offset
        if (result <= 0) {
            this.setState({
                total: 0,
            })
        } else {
            this.setState({
                total: result,
            })
        }
    }

    giveModalAlert = () => {
        const btnList = [
            { text: <span>否</span>, onPress: () => {} },
            {
                text: <span>是</span>,
                onPress: () => this.giveConfirm(),
            },
            // {}
        ]
        Modal.alert('是否确认支付', '', btnList)
    }

    giveConfirm = () => {
        const selectedItem = this.state.selectGift
        selectedItem.giftnum = this.state.total
        selectedItem.UsePack = this.state.showPack ? 1 : 0
        selectedItem.Who = this.state.curIndex === 0 ? 'zhu' : 'ke'
        this.props.onSendGift(selectedItem).then(() => {
            this.setState({
                giftSend: true,
            }, () => this.onPopClose('gift'))
        })
    }

    onPopClose = (key) => {
        // this.initState()
        // const giftSend = this.state.giftSend
        // const select = this.state.selectGift
        // if (select) {
        //     this.getGift()
        //     if (giftSend) {
        //         this.getUserDetail()
        //     }
        // }
        this.getGift()
        this.getUserDetail()
        this.props.onClose(key)
    }

    changeShowType = () => {
        const showPack = this.state.showPack
        this.setState({
            showPack: !showPack,
        })
    }

    render() {
        const {
            // userDetail: {Gold,},
            visible,
            onClose,
        } = this.props
        const Gold = this.state.gold
        const list = this.state.list
        const myList = this.state.myList
        const total = this.state.total
        const selectGift = this.state.selectGift
        let confirmClickable = selectGift && total >= 1
        const showPack = this.state.showPack
        const showList = showPack ? myList : list

        const template = (
            <Modal
                popup
                visible={visible}
                afterClose={this.props.afterClose}
                // onClose={() => this.onPopClose('gift')}
                onClose={() => this.props.onClose('gift')}
                animationType="slide-up"
                iconUrl={RoundGiftIcon}
                Gold={Gold}
            >
                <div className='chat-room-popup-ctn'>
                    <div style={{textAlign: 'left', position: 'absolute', left: '12px', top: '12px',}}>
                        <p className='mg-b-4px' style={{fontSize: '10px',}}>我的余额</p>
                        <div className='chat-room-popup-res-coin flex-align-center'>
                            <img
                                src={SmallCoinIcon}
                                alt=''
                            />
                            <span>{Gold}</span>
                        </div>
                    </div>
                    <div
                        style={{position: 'absolute', right: '12px', top: '12px', textAlign: 'center',}}
                        onClick={this.changeShowType}
                    >
                        <img src={showPack ? giftSrc : bagSrc} alt='' style={{width: 24, height: 24, marginBottom: '4px',}}/>
                        <p style={{fontSize: '10px',}}>{showPack ? '礼物' : '道具包'}</p>
                    </div>

                    <GiftPopupTab
                        tabs={this.state.tabs}
                        onTabSelected={this.onTabClick}
                    />
                    <div
                        style={{
                            background: '#F8F8F8',
                        }}
                    >
                        <GiftList
                            showData={showList}
                            onGiftSelected={this.onGiftSelected}
                        />
                        <div style={{padding: '16px',}}>
                            <GiftCount
                                changeTotal={this.changeTotal}
                                total={this.state.total}
                            />
                            <WhiteSpace size='xl'/>
                            <GiftPopupBtns
                                giveConfirm={this.props.fromPlan ? () => this.giveModalAlert() : () => this.giveConfirm()}
                                onClose={onClose}
                                confirmClickable={confirmClickable}
                            />
                        </div>
                    </div>
                </div>

            </Modal>
        )

        return template
    }
}

const mapDispatchToProps = (dispatch) => ({
    fetchUserDetail: (id) => dispatch.user.fetchUserDetail(id),
})

export default connect(null, mapDispatchToProps)(TogetherGiftPopup)
